package com.theme.passport.controller.app;

import com.theme.common.base.JSONHandler;
import com.theme.common.base.PinYinUtils;
import com.theme.common.mvc.view.R;
import com.theme.common.third.apple.bean.CusJws;
import com.theme.common.third.apple.bean.JwsPayload;
import com.theme.passport.controller.app.utils.JwtUtils;
import com.theme.passport.entity.ThirdUserEntity;
import com.theme.passport.entity.UserEntity;
import com.theme.passport.entity.constant.UserOriginEnum;
import com.theme.passport.form.AppleLoginForm;
import com.theme.passport.service.AppleLoginService;
import com.theme.passport.service.ThirdUserService;
import com.theme.passport.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @name: AppleLoginController <tb>
 * @title: Apple登录接口  <tb>
 * @author: cuixinfu@51play.com <tb>
 * @date: 2021/10/22 15:37:53 <tb>
 */
@RestController
@RequestMapping("app/apple")
@Api("Apple登录接口")
public class AppleLoginController {

    private static final Logger logger = LoggerFactory.getLogger(AppleLoginController.class);

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private ThirdUserService thirdUserService;
    @Autowired
    private AppleLoginService appleLoginService;
    @Value("${user.default-avatar}")
    private String defaultAvatar ;

    @PostMapping("login")
    @ApiOperation("第三方登录[苹果账号应用授权登录]")
    public R appleLogin(@Valid AppleLoginForm loginForm) throws Exception{
        logger.info("苹果账号应用授权登录,参数为：{}", JSONHandler.getGson().toJson(loginForm));
        R valid = appleLoginService.appLoginHandler(loginForm.getIdentityToken());
        logger.info("苹果登陆授权 idToken 验证结果：{}" , JSONHandler.objectToJson(valid));
        if (!R.isOk(valid)){
            logger.info("苹果登陆授权 idToken 验证失败!");
            return valid;
        }
        String cusJwsStr = valid.get("cusJws").toString();
        CusJws cusJws = JSONHandler.getGson().fromJson(cusJwsStr, CusJws.class);
        JwsPayload jwsPayload = cusJws.getJwsPayload();
        logger.info("根据identityToken解析苹果用户信息：jwsPayload：{}", JSONHandler.getGson().toJson(cusJws.getJwsHeader()));
        logger.info("苹果identityToken解析苹果用户信息：：JwsHeader：{}",JSONHandler.getGson().toJson(cusJws.getJwsPayload()));
        ThirdUserEntity thirdUserEntity = thirdUserService.queryByOpenid(UserOriginEnum.APPLE.getValue(), jwsPayload.getSub());
        if (thirdUserEntity != null){
            UserEntity user = userService.getById(thirdUserEntity.getUserId());
            return saveLoginInfo(user);
        }
        logger.info("根据userid-sub：{},获取苹果用户信息为空,开始注册用户", jwsPayload.getSub());
        UserEntity userInsert = new UserEntity();
        //userInsert.setUsername(generateOrderNum());
        userInsert.setUsername(PinYinUtils.getPingYin(loginForm.getNickname()));
        userInsert.setNickname(loginForm.getNickname());
        String email = loginForm.getEmail();
        if (email != null){
            userInsert.setEmail(email);
        }else {
            userInsert.setEmail(jwsPayload.getEmail());
        }
        userInsert.setAvatar(defaultAvatar);
        userInsert.setCountry("-");
        userInsert.setProvince("-");
        userInsert.setCity("-");
        userInsert.setGender(0);
        userInsert.setOrigin(UserOriginEnum.APPLE.getValue());
        userInsert.setOpenid(jwsPayload.getSub());
        // 1、注册用户-apple
        UserEntity resultUser = userService.registerUser(userInsert);
        // 2、保存用户登录信息
        return saveLoginInfo(resultUser);
    }

    public R saveLoginInfo(UserEntity user) {
        if (user == null){
            return R.error("用户登录失败,请稍后重试!");
        }
        //生成token
        String token = jwtUtils.generateToken(user.getId());

        Map<String, Object> map = new HashMap<>();
        user.setPassword("");
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("user", user);

        return R.ok(map);
    }

}
